package com.ruoyi.web.ydz.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.ydz.domain.*;
import com.ruoyi.web.ydz.mapper.InvitationLikeMapper;
import com.ruoyi.web.ydz.mapper.ReplyLikeMapper;
import com.ruoyi.web.ydz.mapper.ReplyMapper;
import com.ruoyi.web.ydz.service.IAttachFileService;
import com.ruoyi.web.ydz.service.IReplyService;
import com.ruoyi.web.ydz.util.areaUtil.AreaUtil;
import com.ruoyi.web.ydz.util.sensitiveFilter.FileToList;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 帖子回复Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-29
 */
@Service
public class ReplyServiceImpl implements IReplyService {
    @Resource
    private ReplyMapper replyMapper;

    @Resource
    private AreaUtil areaUtil;

    @Resource
    private InvitationServiceImpl invitationService;

    @Resource
    private FileToList fileToList;

    @Resource
    private IAttachFileService AttachFileService;

    @Resource
    private InvitationLikeMapper invitationLikeMapper;

    @Resource
    private ReplyLikeMapper replyLikeMapper;

    /**
     * 查询帖子回复
     *
     * @param id 帖子回复主键
     * @return 帖子回复
     */
    @Override
    public Reply selectReplyById(Long id) {
        return replyMapper.selectReplyById(id);
    }

    /**
     * 查询帖子回复列表
     *
     * @param reply 帖子回复
     * @return 帖子回复
     */
    @Override
    public List<Reply> selectReplyList(Reply reply) {
        return replyMapper.selectReplyList(reply);
    }

    /**
     * 新增帖子回复
     *
     * @param reply 帖子回复
     * @return 结果
     */
    @Override
    public int insertReply(Reply reply, HttpServletRequest request) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        reply.setCreateTime(DateUtils.getNowDate());
        reply.setCreateBy(user.getUserName());
        reply.setCreateName(user.getNickName());

        reply.setUserId(user.getUserId());

        /*获取ip*/
        HashMap clientIp = areaUtil.getClientIp(request);
        reply.setUserIp(Objects.isNull(clientIp.get("ip")) ? "未知" : String.valueOf(clientIp.get("ip")));
        reply.setUserArea(Objects.isNull(clientIp.get("area")) ? "未知" : String.valueOf(clientIp.get("area")));

        return replyMapper.insertReply(reply);
    }

    /**
     * 修改帖子回复
     *
     * @param reply 帖子回复
     * @return 结果
     */
    @Override
    public int updateReply(Reply reply) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        reply.setUpdateTime(DateUtils.getNowDate());
        reply.setUpdateBy(user.getUserName());
        reply.setUpdateName(user.getNickName());
        return replyMapper.updateReply(reply);
    }

    @Override
    public int editStatus(Reply reply) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        reply.setUpdateTime(DateUtils.getNowDate());
        reply.setUpdateBy(user.getUserName());
        reply.setUpdateName(user.getNickName());
        return replyMapper.updateReply(reply);
    }

    /**
     * 批量删除帖子回复
     *
     * @param ids 需要删除的帖子回复主键
     * @return 结果
     */
    @Override
    public int deleteReplyByIds(Long[] ids) {
        return replyMapper.deleteReplyByIds(ids);
    }

    /**
     * 删除帖子回复信息
     *
     * @param id 帖子回复主键
     * @return 结果
     */
    @Override
    public int deleteReplyById(Long id) {
        return replyMapper.deleteReplyById(id);
    }

    @Override
    public Long getReplyCount(Long invitationId) {
        return replyMapper.getReplyCount(invitationId);
    }

    @Override
    public AjaxResult getAnyReply(Long replyId) {

        AjaxResult ajaxResult = new AjaxResult();

        try {
            /*当前回复的最大父级*/
            Reply replyPid = replyMapper.selectReplyById(replyId);

            /*
             * 如果当前用户身份不是管理员
             * 则无法查看封禁帖子及回复
             * */
            Boolean isAdmin = false;
            SysUser user = SecurityUtils.getLoginUser().getUser();
            List<SysRole> roles = user.getRoles();
            if (!Objects.isNull(roles)) {
                isAdmin = roles.stream()
                        .anyMatch(bean -> bean.getRoleId().longValue() == 100) ? false : true;
            } else {
                isAdmin = false;
            }

            if (Objects.isNull(replyPid)) {
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "查询成功");
                ajaxResult.put("data", null);
                return ajaxResult;
            } else if ("1".equals(replyPid.getReplyBan()) && !isAdmin) {
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "查询成功");
                ajaxResult.put("data", null);
                return ajaxResult;
            }

            /*查看当前用户是否点赞*/
            boolean isLike = fileToList.isMemberOfSet("Reply:ReplyLikesUser:" + replyPid.getInvitationId() + ":" + replyPid.getId(), "\"" + user.getUserId() + "\"");
            replyPid.setIsLike(isLike);

            /*判断当前评论是否为自己所属*/
            if (user.getUserId().longValue() == replyPid.getUserId().longValue()) {
                replyPid.setIsOwner(true);
            } else {
                replyPid.setIsOwner(false);
            }

            HashMap<String, Object> paraMap = new HashMap<>();
            paraMap.put("replyId", replyPid.getId());

            /*当前回复的帖子下面全部的回复*/
            Reply reply = new Reply();
            reply.setInvitationId(replyPid.getInvitationId());
            if (!isAdmin) {
                reply.setReplyBan("0");
                paraMap.put("isBan", 0);
            }
            List<Reply> anyReply = replyMapper.selectReplyList(reply);

            /*查询当前用户是否点赞*/
            anyReply.forEach(item -> {
                // 获取当前回复下的点赞数及当前用户是否点赞
                boolean replyisLike = fileToList.isMemberOfSet("Reply:ReplyLikesUser:" + replyPid.getInvitationId() + ":" + item.getId(), "\"" + user.getUserId() + "\"");
                item.setIsLike(replyisLike);

                /*判断当前评论是否为自己所属*/
                if (user.getUserId().longValue() == item.getUserId().longValue()) {
                    item.setIsOwner(true);
                } else {
                    item.setIsOwner(false);
                }

            });
            /*查看当前回复子集回复量*/
            Long replyCountByReplyId = replyMapper.getReplyCountByReplyId(paraMap);
            replyPid.setReplyCount(Objects.isNull(replyCountByReplyId) ? 0 : replyCountByReplyId);

            invitationService.addChildRepliesAny(replyPid, anyReply, replyPid);
            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("data", replyPid);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询错误,请联系管理员");
            ajaxResult.put("data", e.getMessage());
        }

        return ajaxResult;
    }

    public AjaxResult getForUsReply() {

        AjaxResult ajaxResult = new AjaxResult();

        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            List<Reply> forUsReply = replyMapper.getForUsReply(user.getUserId());

            if (!Objects.isNull(forUsReply)) {
                forUsReply.forEach(bean -> {

                    /*获取当前回复所属帖子的所有图片*/
                    AttachFile attachFile = new AttachFile();
                    attachFile.setSourceId(bean.getInvitationId());
                    attachFile.setFileClass("03");
                    List<AttachFile> attachFiles = AttachFileService.selectAttachFileList(attachFile);
                    bean.setAttachFiles(attachFiles);

                });
            }

            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("data", forUsReply);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询失败,请联系管理员");
        }

        return ajaxResult;
    }

    public AjaxResult getForUsLike() {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            HashMap<String, Object> resultMap = new HashMap<>();
            SysUser user = SecurityUtils.getLoginUser().getUser();

            /*获取对帖子点赞的信息*/
            List<InvitationLike> invitationLikes = invitationLikeMapper.getForUsInvitationLike(user.getUserId());
            if (!Objects.isNull(invitationLikes)) {
                invitationLikes.forEach(bean -> {

                    /*获取当前回复所属帖子的所有图片*/
                    AttachFile attachFile = new AttachFile();
                    attachFile.setSourceId(bean.getInvitationId());
                    attachFile.setFileClass("03");
                    List<AttachFile> attachFiles = AttachFileService.selectAttachFileList(attachFile);
                    bean.setAttachFiles(attachFiles);

                });
            }

            /*获取对回复点赞的信息*/
            List<ReplyLike> replyLikes = replyLikeMapper.getForUsReplyLike(user.getUserId());
            if (!Objects.isNull(replyLikes)) {
                replyLikes.forEach(bean -> {

                    /*获取当前回复所属帖子的所有图片*/
                    AttachFile attachFile = new AttachFile();
                    attachFile.setSourceId(bean.getInvitationId());
                    attachFile.setFileClass("03");
                    List<AttachFile> attachFiles = AttachFileService.selectAttachFileList(attachFile);
                    bean.setAttachFiles(attachFiles);

                });
            }

            resultMap.put("replyLikes", replyLikes);
            resultMap.put("invitationLikes", invitationLikes);

            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("data", resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询失败,请联系管理员");
        }

        return ajaxResult;
    }

    /*
     * 查看我对 帖子及回复 点赞列表
     * */
    public AjaxResult getToOtherLike() {
        AjaxResult ajaxResult = new AjaxResult();

        try {

            SysUser user = SecurityUtils.getLoginUser().getUser();
            HashMap<String, Object> resultMap = new HashMap<>();

            /*查询出当前用户点赞的 帖子*/
            List<InvitationLike> invitationLikes = invitationLikeMapper.getToOtherInvitationLike(user.getUserId());
            resultMap.put("invitationLikes", invitationLikes);

            /*查询出当前用户点赞的 评论*/
            List<ReplyLike> ReplyLikes = replyLikeMapper.getToOtherReplyLike(user.getUserId());
            resultMap.put("ReplyLikes", ReplyLikes);

            ajaxResult.put("data", resultMap);
            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询失败,请联系管理员");
        }

        return ajaxResult;
    }

    /*查看我对 帖子及回复 评论列表*/
    public AjaxResult getToOtherReply() {
        AjaxResult ajaxResult = new AjaxResult();

        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            List<Reply> toOtherReply = replyMapper.getToOtherReply(user.getUserId());

            ajaxResult.put("data", toOtherReply);
            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");
        } catch (Exception e) {
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询失败,请联系管理员");
            e.printStackTrace();
        }

        return ajaxResult;
    }
}
